import 'dart:async';
import 'dart:io';

import 'package:aichat_flutter_wallet/module/module_dapp/widgets/hover_status.dart';
import 'package:aichat_flutter_wallet/module/module_trade/widgets/circle_progress.dart';
import 'package:aichat_flutter_wallet/module_common/provider/token_list_provider.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';

import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/utils/sign.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/easyloading.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/select_token_dialog.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/transfer_dialog.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/home_bar/home_bar.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/token_widget/token_logo.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easy_permission/constants.dart';
import 'package:flutter_easy_permission/flutter_easy_permission.dart';
import 'package:flutter_scankit/flutter_scankit.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';
import 'package:lib_util/utils/utils.dart';
import 'package:lib_web3/lib_web3.dart';
import '../../../kai_print.dart';
import '../widgets/about_gas.dart';
import '../widgets/gas_list.dart';
import '../widgets/warn_tips.dart';
import './scan_test.dart';

class gasfeeTime extends StatefulWidget {
  bool status;
  Function callback;
  gasfeeTime({required this.status, required this.callback});
  @override
  _gasfeeTime createState() => _gasfeeTime();
}

class _gasfeeTime extends State<gasfeeTime> {
  int _num = 15;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
  }

  void startCountdown() {
    const oneSec = const Duration(seconds: 1);
    _timer = Timer.periodic(oneSec, (Timer timer) {
      if (_num < 1) {
        timer.cancel();
      } else {
        if (mounted)
          setState(() {
            _num = _num - 1;
          });
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(Object context) {
    if (!widget.status && _num == 15 && _timer == null) {
      startCountdown();
    } else if (widget.status) {
      _timer?.cancel();
      _timer = null;
      _num = 15;
    }
    return Row(
      children: [
        Container(
          width: 14.w,
          height: 14.w,
          child: widget.status
              ? CircularProgressIndicator(
                  strokeWidth: 2.w,
                  color: Color.fromRGBO(134, 131, 145, 1),
                )
              : Center(
                  child: CountdownProgressBar(
                      totalTime: 15,
                      progressColor: Color.fromRGBO(134, 131, 145, 1),
                      onCountdownFinish: () {
                        widget.callback();
                      }),
                ),
        ),
        SizedBox(
          width: 6.w,
        ),
        Container(
            alignment: Alignment.centerLeft,
            child: Text(
              widget.status ? 'Loading...' : 'Update in $_num\s',
              style: TextStyle(fontSize: 12.sp, fontWeight: FontWeight.w400, color: AppColors.c_868391),
            )),
      ],
    );
  }
}

class TradeTransferPage extends StatefulWidget {
  final String contract;
  final String? toAddress;
  final bool? twoBack;
  const TradeTransferPage({super.key, required this.contract, this.toAddress, this.twoBack = false});
  @override
  _TradeTransferPage createState() => _TradeTransferPage();
}

class _TradeTransferPage extends State<TradeTransferPage> {
  final TextEditingController _addressController = TextEditingController();
  final TextEditingController _amountController = TextEditingController();
  final FocusNode _addressFocusNode = FocusNode();
  final FocusNode _amountFocusNode = FocusNode();
  bool _gasLoading = true;
  Token? _token;
  Token? _main;
  String _from = '';
  int _gas = 0;
  int _gasPrice = 0;
  int _gasType = 1;
  List<int> gasPriceList = List.generate(3, (index) => 0);
  Map<String, dynamic> transferDetails = {};
  String addressErr = '';
  String banlanceErr = '';
  String rpc = '';
  late ScanKit? scanKit;
  late FlutterEasyPermission _easyPermission;

  void _getToken() {
    // List<Token> allList= ObjectBox().tokenModel.getTokenListAll();
    // for(var itemList in allList){
    //   print('itemList $itemList');
    // }
    // print('context.read<TokenListNotifier>().walletInfoId ${context.read<TokenListNotifier>().walletInfoId}');
    List<Token> _tokenList =
        ObjectBox().tokenModel.getIsAddedTokenListByWalletInfoId(context.read<TokenListNotifier>().walletInfoId);
    kaiPrint('_tokenList -> ${_tokenList}');
    _token = _tokenList.firstWhereOrNull((token) => token.contract == widget.contract);
    // _token =
    // _tokenList.firstWhere((token) => token.contract == widget.contract);
    kaiPrint('_token -> ${_token}');
    if (_token == null) {
      return;
    }

    _main = _tokenList.firstWhere((token) => token.contractType == 'native');
    kaiPrint('_main ${_main}');
    _from = context.read<WalletInfoNotifier>().walletAddress;
    Chain? chain = _token?.getChain();
    rpc = ObjectBox().nodeInfoModel.getSelectedNodeInfo(chain!.shortName).url;
    transferDetails['token'] = _token;
    transferDetails['main'] = _main;
    transferDetails['from'] = _from;
  }

  Future getBalance(Token? token, {bool isUpdate = true}) async {
    Chain? chain = _token?.getChain();
    WalletInfo? _walletInfo = ObjectBox().walletInfoModel.getWalletInfoById(token!.walletInfoId);
    String? balance = token.balance;
    try {
      //以太系列
      if (chain?.type == ChainType.eth) {
        if (token.contractType == 'native') {
          //主币
          balance = await FlutterWeb3.getMainTokenBalance(rpc, _walletInfo!.address);
        } else if (token.contractType == 'token20') {
          //代币
          balance =
              await FlutterWeb3.getTokenBalance(rpc, token.contract, _walletInfo!.address, decimals: token.decimals);
        }
      }
      token.balance = balance;
      context.read<TokenListNotifier>().updateTokens(token);
      if (isUpdate) {
        setState(() {
          _token = token;
          token.contractType == 'native' ? _main = token : '';
        });
      }
      return token.balance;
    } catch (e) {
      return token.balance;
    }
  }

  void _getGasFee() async {
    try {
      setState(() {
        _gasLoading = true;
      });
      Chain? chain = _token?.getChain();
      Map<String, dynamic>? value = await Sign.getErc20Gas(rpc, _token!.contractType, '', chain!.symbol);
      if (chain.type == ChainType.eth) {
        if (value!['gasPrice'] == 0 || value['gas'] == 0) return;
        gasPriceList[0] = (value['gasPrice'] * 1.5).floor();
        gasPriceList[1] = value['gasPrice'];
        gasPriceList[2] = (value['gasPrice'] * 0.75).floor();
      }
      if(chain.type == ChainType.sol){
        if (value!['gasPrice'] == 0 || value['gas'] == 0) return;
        gasPriceList[0] = value['gasPrice'];
        gasPriceList[1] = value['gasPrice'];
        gasPriceList[2] = value['gasPrice'];
      }
      if(chain.type == ChainType.tron){
        if (value!['gasPrice'] == 0 || value['gas'] == 0) return;
        gasPriceList[0] = (value['gasPrice'] * 1.5).floor();
        gasPriceList[1] = value['gasPrice'];
        gasPriceList[2] = (value['gasPrice'] * 0.75).floor();
      }
      _gas = value!['gas'];
      transferDetails['gas'] = value['gas'];
      transferDetails['gasPrice'] = gasPriceList[_gasType];
      _gasPrice = value['gasPrice'];
      _gasLoading = false;
      if (mounted)
        setState(() {
        });
    } catch (err) {
      Log.logger.e('err $err');
      if (mounted)
        setState(() {
          _gasLoading = false;
        });
    }
  }

  _changeToken() {
    Utils.showBottomSheetDialog(context, SelectTokenDialog(title: 'Select Token', token: _token!)).then((value) async {
      if (value == null) return;
      setState(() {
        _token = value;
        Chain? chain = _token?.getChain();
        rpc = ObjectBox().nodeInfoModel.getSelectedNodeInfo(chain!.shortName).url;
        _main = ObjectBox().tokenModel.getMainTokenByWalletInfoId(_token!.walletInfoId);
        WalletInfo? _walletInfo = ObjectBox().walletInfoModel.getWalletInfoById(_token!.walletInfoId);
        _from = _walletInfo!.address;
        transferDetails['token'] = _token;
        transferDetails['main'] = _main;
        transferDetails['from'] = _from;
        // _addressController.text = '';
        _amountController.text = '';
        transferDetails['gas'] = 0;
        transferDetails['gasPrice'] = 0;
        _gas = 0;
        _gasPrice = 0;
        _getGasFee();
      });
      getBalance(_token);
    });
  }

  void selectGasType(int type) {
    Chain? chain = _token?.getChain();
    if (chain!.type == ChainType.eth) {
      _gasPrice = gasPriceList[type];
      transferDetails['gasPrice'] = _gasPrice;
      _gasType = type;
    }
  }

  void startScan() async {
    try {
      const permissions = [Permissions.CAMERA];
      const permissionGroup = [PermissionGroup.Camera];

      bool isHad = await FlutterEasyPermission.has(perms: permissions, permsGroup: permissionGroup);
      if (!isHad) {
        FlutterEasyPermission.request(
            perms: permissions,
            permsGroup: permissionGroup,
            rationale: "Scanning requires obtaining the camera permission of your phone");
        return;
      }
      if (Platform.isAndroid) {
        try {
          await scanKit!.startScan();
        } on PlatformException {
          //  监听 错误类型
        }
        return;
      }
      var val = await Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
        return CustomView();
      }));
      handleScanData(val);
    } catch (e) {
      kaiPrint(e);
    }
  }

  void handleScanData(String val) {
    try {
      var isBool = val.indexOf(':') > -1;
      dynamic originalDataValue = val;
      Log.logger.e(originalDataValue);
      if (isBool) {
        originalDataValue = val.split(':');
        originalDataValue = originalDataValue.length > 0 ? originalDataValue[1] : val;
      }
      //现在发现还有一些二维码是这样的类型的，"ethereum:0x4D440d6A6b4391deDd8799815988e7A4c87b8c64@1"所以还要去掉后面@的内容
      if (originalDataValue.indexOf('@') > -1) {
        originalDataValue = originalDataValue.split('@').first;
      }
      kaiPrint('Utils.isSolana(originalDataValue) ${Utils.isSolana(originalDataValue)}');
      if (Utils.isEthereumAddress(originalDataValue) || Utils.isTronAddress(originalDataValue)|| Utils.isSolana(originalDataValue)) {
        setState(() {
          _addressController.text = originalDataValue;
        });
        return;
      }
      return setState(() {
        addressErr = 'Invalid wallet address';
      });
    } catch (e) {
      kaiPrint('originalDataValue catch => ${e}');
      return setState(() {
        addressErr = 'Invalid wallet address';
      });
    }
  }

  showSendTran() async {
    setState(() {
      banlanceErr = '';
      addressErr = '';
    });
    String address = _addressController.text;
    String amount = _amountController.text;
    if (transferDetails['gas'] == null) transferDetails['gas'] = 0;
    if (transferDetails['gasPrice'] == null) transferDetails['gasPrice'] = 0;
    int gas = transferDetails['gas'];
    int gasPrice = transferDetails['gasPrice'];
    kaiPrint('showSendTran $gasPrice');
    if (address.isEmpty || amount.isEmpty) return;
    //地址无效
    if ((!Utils.isEthereumAddress(address) && _token?.getChain()?.type == ChainType.eth) ||
        (!Utils.isTronAddress(address) && _token?.getChain()?.type == ChainType.tron)) {
      return setState(() {
        addressErr = 'Invalid wallet address';
      });
    }
    // 金额无效
    if (double.parse(amount) <= 0) {
      return setState(() {
        banlanceErr = 'Insufficient balance';
      });
    }

    Token? token = _token?.contractType == 'native' ? _token : _main;
    double gasFee = double.parse((BigInt.from(gas * gasPrice) / BigInt.from(10).pow(_main?.decimals ?? 18)).toString());
    EasyLoading.generateLoadingFuture(getBalance(token, isUpdate: _token?.contractType == 'native')).then((value) {
      // 主币金额无效
      if (_token?.contractType == 'native') {
        if (double.parse(_token?.balance ?? '0') < (gasFee + double.parse(amount))) {
          return setState(() {
            banlanceErr = 'Insufficient balance';
          });
        }
      } else if (_token?.contractType == 'token20') {
        //代币余额不足
        if (double.parse(amount) > double.parse(_token?.balance ?? '0')) {
          return setState(() {
            banlanceErr = 'Insufficient balance';
          });
        }
        //gas不足
        if (gasFee > double.parse(_main?.balance ?? '0')) {
          Toast.show(context,
              status: '2',
              position: Dpositon.bottom,
              message: 'Insufficient gas',
              duration: Duration(milliseconds: 2000));
          return;
        }
      }
      transferDetails['value'] = _amountController.text;
      transferDetails['to'] = _addressController.text;
      kaiPrint('transferDetails $transferDetails');
      Utils.showBottomSheetDialog(context,
          TransferDialog(title: 'Transfer confirmation', transferDetails: transferDetails, twoBack: widget.twoBack));
    }).onError((error, stackTrace) {
      kaiPrint('$error');
      Navigator.of(context).pop();
    });
  }

  void clickAll() {
    setState(() {
      banlanceErr = '';
    });
    if (_token?.contractType == 'native') {
      String gasFee = Utils.formatStringBalance(
          (BigInt.parse(_gas.toString()) * BigInt.parse(gasPriceList[_gasType].toString()) / BigInt.from(10).pow(18))
              .toString(),
          fractionDigits: Config.gasFeeFixedNum);

      String balance =
          Utils.formatStringBalance(_token?.balance, fractionDigits: Config.balanceFixedNum, trimDecimalZero: true);
      if (double.parse(balance) > double.parse(gasFee)) {
        _amountController.text = Utils.formatStringBalance((double.parse(balance) - double.parse(gasFee)).toString(),
            fractionDigits: Config.balanceFixedNum, trimDecimalZero: true);
      } else {
        setState(() {
          banlanceErr = 'Insufficient balance';
        });
      }
    } else {
      _amountController.text =
          Utils.formatStringBalance(_token?.balance, fractionDigits: Config.balanceFixedNum, trimDecimalZero: true);
    }
  }

  Widget Warnbox() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(15.w),
      decoration: BoxDecoration(
        border: Border.all(color: AppColors.c_E0E0E0, width: 1.w),
        borderRadius: BorderRadius.all(Radius.circular(10.w)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Safety Warning',
            style: TextStyle(fontSize: 14.sp, color: Color.fromRGBO(51, 51, 51, 1), fontWeight: FontWeight.w500),
          ),
          SizedBox(
            height: 6.w,
          ),
          Text(
            'You are currently in the process of transferring. Please ensure that your receiving address and the current sending wallet address are on the same blockchain network, otherwise your assets may be lost!',
            style:
                TextStyle(fontSize: 12.sp, color: AppColors.c_868391, fontWeight: FontWeight.w400, height: 16.w / 12.w),
          ),
          SizedBox(
            height: 4.w,
          ),
          Text(
            'Current Network: ${_token!.getChain()!.name}',
            style:
                TextStyle(fontSize: 12.sp, color: AppColors.c_333333, fontWeight: FontWeight.w400, height: 16.w / 12.w),
          )
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) {
      scanKit = ScanKit();
      scanKit!.onResult.listen((val) {
        debugPrint("scanning result:${val.originalValue}  scanType:${val.scanType}");
        handleScanData(val.originalValue);
      });
    }
    // WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    //   _requestTokenList();
    // });
    getData();
  }

  // _requestTokenList() {
  //   return context.read<TokenListNotifier>().refreshTokenListFromServer();
  // }

  getData() async {
    _addressController.text = widget.toAddress ?? '';
    _getToken();
    _getGasFee();
    getBalance(_token);

    _easyPermission = FlutterEasyPermission()
      ..addPermissionCallback(
        onGranted: (requestCode, perms, perm) {
          debugPrint("Android Authorized:$perms");
          debugPrint("iOS Authorized:$perm");
        },
        onDenied: (requestCode, perms, perm, isPermanent) {
          if (isPermanent) {
            FlutterEasyPermission.showAppSettingsDialog(title: "Camera");
          } else {
            debugPrint("Android Deny authorization:$perms");
            debugPrint("iOS Deny authorization:$perm");
          }
        },
      );
  }

  @override
  void dispose() {
    super.dispose();
    _addressController.dispose();
    _amountController.dispose();
    _addressFocusNode.dispose();
    _amountFocusNode.dispose();
    _easyPermission.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.c_white,
      body: Stack(children: [
        Column(
          children: [
            PageHeaderCom(
              title: 'Transfer',
            ),
            _token == null
                ? Padding(
                    //kaipay入金如果没有添加对应的token就要展示这个提示
                    padding: const EdgeInsets.all(20.0),
                    child: Text(
                      'Your wallet does not support the current cryptocurrency',
                      style:
                          TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w500, color: Color.fromRGBO(51, 51, 51, 1)),
                    ),
                  )
                : Expanded(
                    flex: 1,
                    child: SingleChildScrollView(
                        child: Container(
                      padding: EdgeInsets.fromLTRB(20.w, 10.w, 20.w, 10.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 10.w,
                          ),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Transfer Address',
                                style: TextStyle(
                                    fontSize: 14.sp, fontWeight: FontWeight.w500, color: Color.fromRGBO(51, 51, 51, 1)),
                              ),
                              GestureDetector(
                                onTap: () {
                                  startScan();
                                },
                                child: Padding(
                                  padding: EdgeInsetsDirectional.only(top: 0),
                                  child: Image.asset(
                                    'assets/images/common/scan.png',
                                    width: 20.w,
                                    height: 20.w,
                                  ),
                                ),
                              )
                              // Visibility(
                              //     visible: false,
                              //     child: GestureDetector(
                              //       onTap: () async {},
                              //       child: Row(
                              //         crossAxisAlignment: CrossAxisAlignment.center,
                              //         children: [
                              //           Text(
                              //             'Choose wallets',
                              //             style: TextStyle(
                              //                 fontSize: 12,
                              //                 fontWeight: FontWeight.w400,
                              //                 color: Color.fromRGBO(134, 131, 145, 1)),
                              //           ),
                              //           SizedBox(
                              //             width: 2,
                              //           ),
                              //           Image.asset(
                              //             'assets/images/common/more.png',
                              //             width: 12,
                              //             height: 12,
                              //           )
                              //         ],
                              //       ),
                              //     ))
                            ],
                          ),
                          SizedBox(
                            height: 10.w,
                          ),
                          Container(
                            padding: EdgeInsets.only(left: 15.w, right: 15.w),
                            decoration: BoxDecoration(
                                color: Color.fromRGBO(246, 246, 246, 1),
                                borderRadius: BorderRadius.all(Radius.circular(10.w))),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: TextField(
                                    inputFormatters: [
                                      // LengthLimitingTextInputFormatter(42),
                                      FilteringTextInputFormatter.allow(RegExp("[a-zA-Z0-9]")),
                                      // 限制输入长度为20个字符
                                    ],
                                    keyboardType: TextInputType.text,
                                    controller: _addressController,
                                    focusNode: _addressFocusNode,
                                    onTapOutside: (PointDownEvent) {
                                      _addressFocusNode.unfocus();
                                    },
                                    onEditingComplete: () {
                                      _addressFocusNode.unfocus();
                                    },
                                    onChanged: (value) {
                                      setState(() {
                                        addressErr = "";
                                      });
                                    },
                                    cursorColor: Color.fromRGBO(134, 103, 254, 1),
                                    style: TextStyle(
                                      fontSize: 15.sp,
                                      height: 20.w / 15.w,
                                      color: Color.fromRGBO(51, 51, 51, 1),
                                      fontWeight: FontWeight.w500,
                                    ),
                                    decoration: InputDecoration(
                                      border: InputBorder.none,
                                      hintText: 'Enter receiving address',
                                      hintStyle: TextStyle(
                                        fontSize: 14.sp,
                                        height: 20.w / 14.w,
                                        color: Color.fromRGBO(190, 189, 202, 1),
                                      ),
                                    ),
                                    minLines: null,
                                    maxLines: null,
                                  ),
                                ),
                                SizedBox(
                                  width: 20.w,
                                ),
                                Visibility(
                                    visible: _addressController.text.isNotEmpty,
                                    child: GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          _addressController.clear();
                                        });
                                      },
                                      child: Padding(
                                        padding: EdgeInsets.only(left: 20.w),
                                        child: Image.asset(
                                          'assets/images/common/clear-input.png',
                                          width: 16.w,
                                          height: 16.w,
                                        ),
                                      ),
                                    ))
                              ],
                            ),
                          ),
                          Visibility(
                              visible: !addressErr.isEmpty,
                              child: WarnTips(
                                  text: addressErr,
                                  onPressed: () {
                                    setState(() {
                                      addressErr = '';
                                    });
                                  })),
                          SizedBox(
                            height: 20.w,
                          ),
                          Container(
                            child: Row(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  'Transfer Amount',
                                  style: TextStyle(
                                      color: Color.fromRGBO(51, 51, 51, 1),
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w500),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    _changeToken();
                                  },
                                  child: Row(
                                    children: [
                                      ClipRRect(
                                        borderRadius: BorderRadius.circular(20.w),
                                        child: TokenLogo(
                                          token: _token!,
                                          size: 18.w,
                                        ),
                                      ),
                                      SizedBox(
                                        width: 5,
                                      ),
                                      Text(
                                        _token!.symbol,
                                        style: TextStyle(
                                            color: Color.fromRGBO(51, 51, 51, 1),
                                            fontSize: 14.sp,
                                            fontWeight: FontWeight.w500),
                                      ),
                                      SizedBox(
                                        width: 5.w,
                                      ),
                                      Image.asset(
                                        'assets/images/wallet-trade/token-more.png',
                                        width: 10.w,
                                        height: 10.w,
                                      ),
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ),
                          SizedBox(
                            height: 10.w,
                          ),
                          Container(
                            padding: EdgeInsets.only(left: 15.w, right: 15.w),
                            decoration: BoxDecoration(
                                color: Color.fromRGBO(246, 246, 246, 1),
                                borderRadius: BorderRadius.all(Radius.circular(10.w))),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: TextField(
                                    inputFormatters: [
                                      FilteringTextInputFormatter.allow(
                                        RegExp(r'^\d*\.?\d{0,18}'),
                                        replacementString: '', //达到条件不让输入
                                      ),

                                      // 限制输入长度为20个字符
                                    ],
                                    keyboardType: TextInputType.numberWithOptions(decimal: true),
                                    controller: _amountController,
                                    focusNode: _amountFocusNode,
                                    onTapOutside: (PointDownEvent) {
                                      _amountFocusNode.unfocus();
                                    },
                                    onEditingComplete: () {
                                      _amountFocusNode.unfocus();
                                    },
                                    onChanged: (value) {
                                      setState(() {
                                        banlanceErr = "";
                                      });
                                    },
                                    cursorColor: Color.fromRGBO(134, 103, 254, 1),
                                    style: TextStyle(
                                        fontSize: 16.sp,
                                        height: 19.w / 16.w,
                                        color: Color.fromRGBO(51, 51, 51, 1),
                                        fontWeight: FontWeight.w500,
                                        fontFamily: '_DIN'),
                                    decoration: InputDecoration(
                                      border: InputBorder.none,
                                      hintText: '0.00',
                                      hintStyle: TextStyle(
                                        fontSize: 16.sp,
                                        height: 19.w / 16.w,
                                        color: Color.fromRGBO(190, 189, 202, 1),
                                      ),
                                    ),
                                    minLines: null,
                                    maxLines: null,
                                  ),
                                ),
                                Visibility(
                                    visible: _amountController.text.isNotEmpty,
                                    child: GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          banlanceErr = 'Insufficient balance';
                                          _amountController.clear();
                                        });
                                      },
                                      child: Padding(
                                        padding: EdgeInsets.only(left: 20.w),
                                        child: Image.asset(
                                          'assets/images/common/clear-input.png',
                                          width: 16.w,
                                          height: 16.w,
                                        ),
                                      ),
                                    )),
                                SizedBox(
                                  width: 10.w,
                                ),
                                GestureDetector(
                                  onTap: () {
                                    clickAll();
                                  },
                                  child: Text(
                                    'All',
                                    style: TextStyle(
                                        color: Color.fromRGBO(134, 103, 254, 1),
                                        fontSize: 14.sp,
                                        fontWeight: FontWeight.w400),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Visibility(
                              visible: !banlanceErr.isEmpty,
                              child: WarnTips(
                                  text: banlanceErr,
                                  onPressed: () {
                                    setState(() {
                                      banlanceErr = '';
                                    });
                                  })),
                          SizedBox(
                            height: 10.w,
                          ),
                          Text.rich(
                            TextSpan(children: [
                              TextSpan(
                                  text: 'Balance:',
                                  style: TextStyle(
                                    fontSize: 12.sp,
                                    height: 17.w / 12.w,
                                    color: AppColors.c_333333,
                                  )),
                              WidgetSpan(
                                child: SizedBox(width: 4.w), // 这里放置了一个SizedBox作为间隔
                              ),
                              TextSpan(
                                text: Utils.formatStringBalance(_token?.balance,
                                    fractionDigits: Config.balanceFixedNum, trimDecimalZero: true),
                                style: TextStyle(
                                    color: AppColors.c_333333,
                                    fontSize: 12.sp,
                                    fontWeight: FontWeight.bold,
                                    fontFamily: '_DIN'),
                              ),
                            ]),
                          ),
                          SizedBox(
                            height: 20.w,
                          ),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    'Estimated Gas Fee',
                                    style: TextStyle(
                                        fontSize: 14.sp,
                                        fontWeight: FontWeight.w500,
                                        color: Color.fromRGBO(51, 51, 51, 1)),
                                  ),
                                  SizedBox(
                                    width: 6.w,
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      AboutGasDialog.showAboutGas(context, chainName: _token?.getChain()?.name ?? '');
                                    },
                                    child: Image.asset('assets/images/wallet-trade/tips-info.png',
                                        width: 14.w, height: 14.w),
                                  )
                                ],
                              ),
                              gasfeeTime(status: _gasLoading, callback: _getGasFee),
                            ],
                          ),
                          SizedBox(
                            height: 10.w,
                          ),
                          GasList(_token, _main, _gas, gasPriceList, (int type) {
                            selectGasType(type);
                          }),
                          SizedBox(
                            height: 20.w,
                          ),
                          Warnbox(),
                          SizedBox(
                            height: 75.w,
                          )
                        ],
                      ),
                    ))),
          ],
        ),
        Positioned(
            bottom: 0,
            right: 0,
            left: 0,
            child: Container(
              alignment: Alignment.center,
              color: Colors.white,
              padding: EdgeInsets.symmetric(vertical: 10.w, horizontal: 20.w),
              child: Column(
                children: [
                  HoverStatus(
                    defaultColor: (_addressController.text.isEmpty || _amountController.text.isEmpty)
                        ? Color.fromRGBO(183, 165, 255, 1)
                        : Color.fromRGBO(134, 103, 254, 1),
                    hoverColor: (_addressController.text.isEmpty || _amountController.text.isEmpty)
                        ? Color.fromRGBO(183, 165, 255, 1)
                        : Color.fromRGBO(109, 77, 231, 1),
                    radius: 10.w,
                    child: Container(
                      width: double.infinity,
                      height: 46.w,
                      alignment: Alignment.center,
                      child: Text(
                        'Confirm',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w500,
                          color: (_addressController.text.isEmpty || _amountController.text.isEmpty)
                              ? Color.fromRGBO(255, 255, 255, 0.5)
                              : Color.fromRGBO(255, 255, 255, 1),
                        ),
                      ),
                    ),
                    onPressed: () async {
                      showSendTran();
                    },
                  ),
                  HomeBar(h: 0)
                ],
              ),
            ))
      ]),
    );
  }
}
